package cn.com.thinvent.dispatch.web.controller;

import cn.com.thinvent.dispatch.entity.OrderDetail;
import cn.com.thinvent.dispatch.entity.OrderMain;
import cn.com.thinvent.dispatch.entity.response.OrderMainResponse;
import cn.com.thinvent.dispatch.entity.response.ReturnModel;
import cn.com.thinvent.dispatch.service.biz.OrderService;
import cn.com.thinvent.dispatch.service.biz.ShoppingCartService;
import cn.com.thinvent.dispatch.service.biz.util.KeyGenerator;
import cn.com.thinvent.dispatch.service.biz.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/placeOrder")
    public ReturnModel placeOrder(@RequestParam String menuIds, @RequestParam String orderRemark) {
        try {
            // 生成订单主表
            OrderMain orderMain = new OrderMain();
            orderMain.setId(KeyGenerator.generateKey());
            orderMain.setCreatedById(UserContext.get());
            orderMain.setReceivedById("yjw");
            orderMain.setOrderRemark(orderRemark);
            // TODO 将订单信息发送到18070291816
            orderMain.setCreatedAt(new Date());
            orderMain.setUpdatedAt(new Date());

            // 生成订单子表
            List<OrderDetail> orderDetails = new ArrayList<>();
            String[] menuIdArray = menuIds.split(",");
            for (String menuId : menuIdArray) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setId(KeyGenerator.generateKey());
                orderDetail.setOrderId(orderMain.getId());
                orderDetail.setMenuId(menuId.trim());
                orderDetail.setCreatedAt(new Date());
                orderDetail.setUpdatedAt(new Date());
                orderDetails.add(orderDetail);
            }

            // 保存订单
            orderService.placeOrder(orderMain, orderDetails);
            // 下单成功后删除购物车
            for (String menuId : menuIdArray) {
                shoppingCartService.deleteByMenuIdAndCreatedById(menuId, UserContext.get());
            }
            return new ReturnModel(200, null, "订单创建成功");
        } catch (Exception e) {
            return new ReturnModel(200, null, "订单创建失败: " + e.getMessage());
        }
    }

    @GetMapping("/orderDetails")
    public ReturnModel getOrderDetailsByUserId() {
        try {
            List<OrderMainResponse> orders = orderService.findOrdersByUserId(UserContext.get());
             return new ReturnModel(200, orders, "订单详情获取成功");
        } catch (Exception e) {
            return new ReturnModel(500, null, "订单详情获取失败: " + e.getMessage());
        }
    }

}
